/**
 * @Title: institution_detail_ctrl.js
 * @Description: TODO Copyright: Copyright (c) 2014 Company:中国平安
 * 
 * @Project HIMS-FWA
 * @author EX-chenyonghong001
 * @date 2014年10月17日 下午2:38:47
 * @version V1.0
 */
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.value('CheckRows',{
	});
	app.controller('addDoctorInfoCtrl', ['$scope','CommunityService','$http','$modal','$state','$stateParams','doctorInfoService','BaseURL','Modal','CheckRows',
	                                function($scope,CommunityService,$http,$modal,$state,$stateParams,doctorInfoService,baseUrl,Modal,CheckRows){
	     $scope.UrlParams = $stateParams;
	     $scope.communityService = CommunityService;
	 	 CommunityService.initCodeListDatas();
	     CommunityService.getBaseCode('{codeType:\'provincialDep\'}');
	     CommunityService.getBaseCode('{codeType:\'sex\'}');
	     CommunityService.getBaseCode('{codeType:\'cityDep\'}');
		 CommunityService.getBaseCode('{codeType:\'personTypeHos\'}');
		 CommunityService.getBaseCode('{codeType:\'jobType\'}');
		 CommunityService.getBaseCode('{codeType:\'id_type\'}');
		 CommunityService.getBaseCode('{codeType:\'qualifiedLev\'}');
		 CommunityService.getBaseCode('{codeType:\'workScope\'}');
		 $scope.type =  $scope.UrlParams.type;
		 $scope.doctorId =   $scope.UrlParams.doctorId;
		 $scope.providerid = $scope.UrlParams.providerid;
		 $scope.doctorInfoDetail = {};
         var qualifiedLevel = "";
         var serviceStus = "";
         
         var initInstitutionRows = [];
         $scope.authority={
         		add:0,
         		update:0,
         		deleted:0
         };
         $scope.columns = [ 
                           {
                               label : '执业机构',
                               map : 'providerName',
                               width : '20%'
                               }, {
                               label : '机构等级',
                               map : 'hospitalLevel',
                               width : '19%'
                           }, {
                               label : '医院科室（名称）',
                               map : 'departName',
                               width : '26%'
                           }, {
                               label : '地址',
                               map : 'fullAddress',
                               width : '35%'
                           }];
         $scope.query = function(){
             if($scope.doctorId){
                 $http({
                     method : 'GET',
                     cache : false,
                     url : baseUrl + '/hcp/hcp/insurance/show.do',
                     params : {
                         id : $scope.doctorId
                     }
                 }).success(function(response, status, headers, config) {
                	 $scope.authority=response.authority;
                     $scope.doctorInfoDetail = response.result;
                      qualifiedLevel =  $scope.doctorInfoDetail.qualifiedLevel;
                      serviceStus =  $scope.doctorInfoDetail.serviceStus;
                      initInstitutionRows =$scope.doctorInfoDetail.institutionList;
                      $scope.doctorInfoDetail.checkInstitutionRows = $scope.doctorInfoDetail.institutionList;
                 });
    		 }
         }
         
         $scope.query();
		 $scope.updateList=[];
         
         $scope.updateQualifiedLevel={};
          $scope.$watch("doctorInfoDetail.qualifiedLevel",function(newVal,oldVal){
         	if(newVal && oldVal && newVal != qualifiedLevel){
         		 $scope.updateQualifiedLevel ={
         				 relationid:$scope.doctorId,
         				 changeContent:"资格级别",
         				 changeBefore:qualifiedLevel,
         				 changeAfter:newVal,
         				 codeType:"qualification_level",
         				 changeType:1
         		 }
         	}else{
         		$scope.updateQualifiedLevel ={};
         	}
         	
         })
         
         
         	$scope.updateServiceStus ={};
        $scope.$watch("doctorInfoDetail.serviceStus",function(newVal,oldVal){
         	if(newVal != serviceStus){
         		 $scope.updateServiceStus ={
         				 relationid:$scope.doctorId,
         				 changeContent:"医保服务状态",
         				 changeBefore:serviceStus,
         				 changeAfter:newVal,
         				 codeType:"serviceStus",
         				 changeType:1
         		 }
         	}else{
         		$scope.updateServiceStus ={};
         	}
         	
         });
        
        
        $scope.inputChange = function(){
      	  if($scope.doctorInfoDetail.startDate>$scope.doctorInfoDetail.endDate){
			  Modal.alert( "有效期限结束日期不得早于开始日期！");  
		  }
        }
        
	  $scope.check = function(doctorInfoDetail) {
		  var dateReg =/^\d{4}-\d{2}-\d{2}$/;
		
		  if(!doctorInfoDetail.name){
			  return "姓名不能为空！";					  
		  }
		  if(!doctorInfoDetail.sex){
			  return "性别不能为空！";  
		  }
		  if(!dateReg.test(doctorInfoDetail.birthDate)){
			  return "出生日期不能为空,并且必须输入正确的日期格式(yyyy-MM-dd)！";  
		  }
		  if(!doctorInfoDetail.personType){
			  return "人员分类不能为空！";  
		  }
		  if(!doctorInfoDetail.certificateType){
			  return "证件类型不能为空！";  
		  }
		  if(!doctorInfoDetail.certificateNo){
			  return "证件号不能为空！";  
		  }
		  if(!doctorInfoDetail.insurancenum){
			  return "保险号不能为空！";  
		  }
		  if(!doctorInfoDetail.mobilePhone){
			  return "手机不能为空！";  
		  }
		  if(!doctorInfoDetail.qualifiedLevel){
			  return "资格级别不能为空！";  
		  }
		  if(!dateReg.test(doctorInfoDetail.qualifiedDate)){
			  return "执业授予时间不能为空,并且必须输入正确的日期格式(yyyy-MM-dd)！";  
		  }
		  if(doctorInfoDetail.startDate>doctorInfoDetail.endDate){
			  return "有效期限结束日期不得早于开始日期！";  
		  }
		  
	};
		  

		  function containAddList(initInstitutionRows,tableListRows) {
			  var addList = [];
			  for(var i = 0 ; i < tableListRows.length; i++) {
				  var tableRow = tableListRows[i];
				  if(!isExistRow(initInstitutionRows,tableRow)) {
					  addList.push(tableRow);
				  }
			  }
			  
			  return addList;
		  }
		  
		  function containDelList(initInstitutionRows,tableListRows) {
			  var delList = [];
			  for(var i = 0 ; i < initInstitutionRows.length; i++) {
				  var checkRow = initInstitutionRows[i];
				  if(!contain(checkRow,tableListRows)) {
					  delList.push(checkRow);
				  }
			  }
			  return delList;
		  }
		  
		  function containUpdateList(initInstitutionRows,tableListRows) {
			  var updateList = [];
			  for(var i = 0 ; i < tableListRows.length; i++) {
				  var tableRow = tableListRows[i];
				  if(isModifyDepartCodeRow(initInstitutionRows,tableRow)) {
					  updateList.push(tableRow);
				  }
			  }
			  return updateList;
		  }
		  
		  function contain(tableData,initInstitutionRows){
			  for(var i = 0 ; i < initInstitutionRows.length; i++){
					 var tempData =initInstitutionRows[i];
					 if(tableData.providerId == tempData.providerId){
						return true;
					 }
				  }
			  return false;
		  }
		  
		  function isModifyDepartCodeRow(initInstitutionRows,tableRow) {
			  var updateList = [];
			  for(var j = 0 ; j < initInstitutionRows.length; j++) {
				  var checkoutRow = initInstitutionRows[j]
				  // 如果找到
				  if(tableRow.providerId == checkoutRow.providerId && tableRow.departNo != checkoutRow.departNo) {
					  tableRow.oldDepartName = checkoutRow.departName;
					  return true;
				  }
			  }
			  return false;
		  }
		  
		  //是否存在这条记录，不存在，则标示是添加的记录
		  function isExistRow(initInstitutionRows,tableRow) {
			  for(var j = 0 ; j < initInstitutionRows.length; j++) {
				  var checkoutRow = initInstitutionRows[j]
				  // 如果找不到，则标示是新增记录
				  if(tableRow.providerId == checkoutRow.providerId) {
					  return true;
				  }
			  }
			  return false;
		  }
		  
		  
		  $scope.updateAddrs=[];
		  $scope.updateAddr ={};
		  $scope.getUpdateAddr = function(){
			  var addList = containAddList(initInstitutionRows,$scope.doctorInfoDetail.checkInstitutionRows);
			  var delList = containDelList(initInstitutionRows,$scope.doctorInfoDetail.checkInstitutionRows);
			  var updateList = containUpdateList(initInstitutionRows,$scope.doctorInfoDetail.checkInstitutionRows);
			  
			  for(var i = 0 ; i < addList.length; i++){
				  var addAddr={
	         				 relationid:$scope.doctorId,
	         				 changeContent:"执业地址",
	         				 changeBefore:"无",
	         				 changeAfter:addList[i].providerName,
	         				 codeType:"workAddr",
	         				 changeType:1
					};
					$scope.updateList.push(addAddr);
			  }
			  
			  for(var i = 0 ; i < delList.length; i++){
				  var delAddr={
	         				 relationid:$scope.doctorId,
	         				 changeContent:"执业地址",
	         				 changeBefore:"无",
	         				 changeAfter:delList[i].providerName,
	         				 codeType:"workAddr",
	         				 changeType:1
					};
					$scope.updateList.push(delAddr);
			  }
			  
			  for(var i = 0 ; i < updateList.length; i++){
				  var updateDep ={
	         				 relationid:$scope.doctorId,
	         				 changeContent:"医院科室",
	         				 changeBefore:updateList[i].oldDepartName,
	         				 changeAfter:updateList[i].departName,
	         				 changeType:1
	         		};
					$scope.updateList.push(updateDep);
			  }
		  };
		  
		$scope.saveDoctor = function(){
			var msg = $scope.check($scope.doctorInfoDetail);
			if(msg){
				 Modal.alert(msg);
					 return;
			}
			 var addr = "";
				angular.forEach($scope.doctorInfoDetail.checkInstitutionRows,function(checkData,index){
					addr +=checkData.providerCode+'|' + checkData.departNo + ",";
	    		});
				var position = addr.length-1;
				addr = addr.substring(0, position);
				$scope.doctorInfoDetail.jobAdder = addr;
				$scope.doctorInfoDetail.providerid = $scope.UrlParams.providerid;
			
			 
			 if($scope.doctorId){
				// 医院科室和医疗机构变更记录
				$scope.getUpdateAddr();
				 
         	   if($scope.updateQualifiedLevel.relationid){
              		 $scope.updateList.push($scope.updateQualifiedLevel);
               	}
         	   if($scope.updateServiceStus.relationid){
              		 $scope.updateList.push($scope.updateServiceStus);
               	}
         	   $scope.doctorInfoDetail.updateList = $scope.updateList;
	                $http.post(baseUrl + '/hcp/hcp/insurance/update.do',$scope.doctorInfoDetail).success(function(data) {
                        if(data.state=='0'){
                        	$scope.updateDep={};
                        	$scope.updateParentDep={};
                        	$scope.updateQualifiedLevel={};
                        	$scope.updateServiceStus={};
                        	$scope.updateList=[];
                            Modal.alert(data.msg);
                    		$state.go('insurance.insuranceList');
                        } else {
                            Modal.alert("修改失败！");
                        }

                    })
			 }else{
				$http.post(baseUrl + '/hcp/hcp/insurance/create.do',$scope.doctorInfoDetail).success(function(data) {
		                if(data.state=='0')
		                {
		                    Modal.alert(data.msg);
		        			$state.go('insurance.insuranceList');
		                }else
		                {
		                    Modal.alert("新增失败！");
		                }
		
		            })

			 }
				
		}
		
		$scope.cancel = function(){
			$state.go('insurance.insuranceList');
		}
		$scope.checkInsuranceGrading= function (checked){
			angular.forEach( $scope.doctorInfoDetail.checkInstitutionRows,function(checkData,i){
				checkData.checked = checked;
    		});
		}
		$scope.selectId =[];
		
		 $scope.deleteJobAddr = function (){
			 var tempRows =[];
			angular.forEach( $scope.doctorInfoDetail.checkInstitutionRows,function(checkData,i){
					if(!checkData.checked || checkData.checked === false){
						tempRows.push(checkData);  	
					}
    		});
            Modal.confirm('确认删除吗？',function() {
            	$scope.doctorInfoDetail.checkInstitutionRows = tempRows;
            })
		
		 }
		 
        $scope.addJobAddr = function (doctorId){
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institution/queryInstitution_list.html',
		      backdrop:'static',
			  size:'sm',
			  scope : $scope,
			  controller: 'queryInstitutionListCtrl'
		    });
		    
		    if(!$scope.doctorInfoDetail.checkInstitutionRows){
		        $scope.doctorInfoDetail.checkInstitutionRows = [];
		    }

		    modalInstance.result.then(function (selectedItem) {
		    	$scope.doctorInfoDetail.checkInstitutionRows.push(selectedItem);
		    });
		
        }
        
	}
	]);
})();